package com.controller;

import com.annotation.IgnoreAuth;
import com.entity.CourseEntity;
import com.entity.LessonEntity;
import com.service.CourseService;
import com.service.LearningProgressService;
import com.service.LessonService;
// 导入其他必要的类
import com.service.UserService;
import com.utils.OBSUtil;
import com.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.baomidou.mybatisplus.mapper.EntityWrapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Objects;
import java.util.UUID;


/**
 * 上传文件控制类
 * */
@RestController
@RequestMapping("/api/upload")
public class FileUploadController {

    @Autowired
    private OBSUtil obsUtil;

    @Autowired
    private CourseService courseService;

    @Autowired
    private LessonService lessonService;

    @Autowired
    private LearningProgressService learningProgressService;
    @Autowired
    private UserService userService;


    /**
     * 为指定的【课时】上传视频文件，兼容更改视频功能
     * @param lessonId 课时的ID，通过URL路径传入
     * @param file 视频文件
     * @return 包含视频URL的响应
     */
    @PostMapping("/lesson/video")
    public R uploadLessonVideo(@RequestParam Integer lessonId,
                               @RequestParam("file") MultipartFile file) {
        LessonEntity lesson = lessonService.selectById(lessonId);
        if (lesson == null) {
            return R.error("ID为 " + lessonId + " 的课时不存在。");
        }
        if (!"video".equals(lesson.getLessonType())) {
            return R.error("该课时不是视频类型，无法上传视频。");
        }

        Integer oldDurationSeconds = lesson.getDurationSeconds();
        try {
            String originalFileName = file.getOriginalFilename();
            String fileExtension = "";
            int dotIndex = originalFileName.lastIndexOf('.');
            if (dotIndex > 0) {
                fileExtension = originalFileName.substring(dotIndex);
            }
            String fileName = "lessons/videos/" + UUID.randomUUID() + fileExtension;
            String videoUrl = obsUtil.uploadFile(fileName, file.getInputStream());

            // 自动提取视频时长
            int parsedDuration = getVideoDurationFromUrl(videoUrl);

            lesson.setVideoUrl(videoUrl);
            lesson.setDurationSeconds(parsedDuration);
            lessonService.updateById(lesson);

            if (lesson.getCourseId() != null) {
                //根据新上传的视频计算课程新的总时长
                learningProgressService.updateProgressAfterLessonVideoChange(lessonId, oldDurationSeconds, parsedDuration);
            } else {
                System.err.println("课时 " + lessonId + " 没有关联课程ID，无法更新课程总视频时长。");
            }

            return R.ok("视频上传成功")
                    .put("url", videoUrl)
                    .put("durationSeconds", parsedDuration);

        } catch (IOException e) {
            return R.error("视频文件上传失败: " + e.getMessage());
        } catch (InterruptedException e) {
            return R.error("处理视频时长失败: " + e.getMessage());
        }
    }


    /**
     * 为指定的【课程】上传封面图片
     * @param courseId 课程的ID，通过URL路径传入
     * @param file 图片文件
     * @return 包含图片URL的响应
     */
    @PostMapping("/course/cover")
    public R uploadCourseCoverImage(@RequestParam Long courseId, @RequestParam("file") MultipartFile file) {
        // 【修正点】使用 .selectById()
        CourseEntity course = courseService.selectById(courseId);
        if (course == null) {
            return R.error("ID为 " + courseId + " 的课程不存在。");
        }

        try {
            String fileName = "courses/covers/" + UUID.randomUUID().toString() + "-" + file.getOriginalFilename();
            String imageUrl = obsUtil.uploadFile(fileName, file.getInputStream());

            course.setCoverImageUrl(imageUrl);
            courseService.updateById(course);

            return R.ok("课程封面上传成功").put("url", imageUrl);

        } catch (IOException e) {
            return R.error("图片文件上传失败: " + e.getMessage());
        }
    }

    /**
     * 【示例】为指定的【文章课时】上传PDF文件作为其内容
     */
    @PostMapping("/lesson/pdf")
    public R uploadLessonPdf(@RequestParam Long lessonId, @RequestParam("file") MultipartFile file) {

        LessonEntity lesson = lessonService.selectById(lessonId);
        if (lesson == null) {
            return R.error("ID为 " + lessonId + " 的课时不存在。");
        }

        try {
            String fileName = "lessons/pdfs/" + UUID.randomUUID().toString() + "-" + file.getOriginalFilename();
            String pdfUrl = obsUtil.uploadFile(fileName, file.getInputStream());

            lesson.setPdfUrl(pdfUrl);
            lessonService.updateById(lesson);

            return R.ok("PDF附件上传成功").put("url", pdfUrl);

        } catch (IOException e) {
            return R.error("PDF文件上传失败: " + e.getMessage());
        }
    }

    /**
     * 上传头像
     * */
    @IgnoreAuth
    @PostMapping("/uploadAvatar")
    public R uploadAvatar(@RequestParam("file") MultipartFile file) {
        try {

            String fileName = "avatar/" + UUID.randomUUID().toString() + "-" + file.getOriginalFilename();
            String avatarUrl = obsUtil.uploadFile(fileName, file.getInputStream());
            return R.ok("头像上传成功").put("url", avatarUrl);

        } catch (IOException e) {
            return R.error("头像上传失败: " + e.getMessage());
        }
    }

    /**
     * 上传图片
     * */
    @IgnoreAuth
    @PostMapping("/uploadImage")
    public R uploadImage(@RequestParam("file") MultipartFile file) {
        try {

            String fileName = "images/" + UUID.randomUUID().toString() + "-" + file.getOriginalFilename();
            String imageUrl = obsUtil.uploadFile(fileName, file.getInputStream());
            return R.ok("图片上传成功").put("url", imageUrl);

        } catch (IOException e) {
            return R.error("图片上传失败: " + e.getMessage());
        }
    }

    /**
     * 删除视频或url
     * */
    @PostMapping("/deleteUrl")
    public R deleteUrl(@RequestParam Integer lessonId, @RequestParam("type") String type) {
        LessonEntity lesson=lessonService.selectById(lessonId);

        if(lesson!=null){

            if(Objects.equals(type, "video")){
                Integer duration=lesson.getDurationSeconds();
                lesson.setVideoUrl(null);
                lesson.setDurationSeconds(0);
                learningProgressService.updateProgressAfterLessonVideoChange(lessonId,duration,0);
            }
            else{
                lesson.setPdfUrl(null);
            }
            lessonService.updateById(lesson);
            return R.ok("操作成功");
        }
        else{
            return R.error("未能找到对应课时");
        }
    }

    /**
     * 通过视频url获取视频时长，不用手动输入时长了
     * */
    public int getVideoDurationFromUrl(String videoUrl) throws IOException, InterruptedException {
        ProcessBuilder pb = new ProcessBuilder(
                "ffprobe",
                "-v", "error",
                "-show_entries", "format=duration",
                "-of", "default=noprint_wrappers=1:nokey=1",
                videoUrl
        );

        Process process = pb.start();

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
            String durationStr = reader.readLine();
            int exitCode = process.waitFor();

            if (exitCode != 0 || durationStr == null) {
                throw new IOException("ffprobe 解析失败");
            }

            double seconds = Double.parseDouble(durationStr);
            return (int) Math.round(seconds);
        }
    }
}
